<?php 

/**
* 字母大写与数字的验证码
*/
class Code
{
	public $num=5;	//验证码的字母数量
	public $width=200;
	public $height=100;//画布高度
	public $src;
	public $color1;
	public $font_size=20;//验证码字母大小
	
	function __construct($width="",$height="",$num="",$font_size="")
	{
		$this->width=empty($width)? $this->width:$width;//画布的长
		$this->height=empty($height)? $this->height:$height;//画布的高
		$this->num=empty($num)? $this->num:$num;//字体数量
		$this->font_size=empty($font_size)? $this->font_size:$font_size;//字体高度		 
	}
	public function run(){
		$this->create();	//创建画布并填充颜色
		$this->interfere();		//设置干扰
		$this->ziti();			//设置字体

		$this->output();		//输出图像
	}

	//创建画布并填充颜色
	public function create(){
		header("Content-type: image/png");
		$this->src = imageCreateTrueColor($this->width,$this->height); //创建画布
		$color=imagecolorallocate($this->src, 122, 162, 58); //设置颜色
		imagefill($this->src, 0, 0, $color); //在画布上填充颜色
		 
	}

	//设置干扰
	public function interfere(){
		//点干扰
		$this->color1=imagecolorallocate($this->src, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));
		for ($i=0; $i <80 ; $i++) { 
		imagesetpixel($this->src, mt_rand(0,200), mt_rand(0,100), $this->color1);
		};

		// 线干扰
		for ($n=0; $n <30 ; $n++) { 
			// $start1=mt_rand($x*$n,($x/2)+($x*$n));
			// $start2=mt_rand(0,$this->height);
			// $end1=mt_rand(($x/2)+($x*$n)+$n,$x);
			// $end2=mt_rand(0,$this->height);
			$color_line=imagecolorallocate($this->src, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));
			imageline($this->src,mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height),$color_line);		
		}		
	}

	// 设置字体
	public function ziti(){
		$zimu="qwertyuiopasdfghjklzxcvbnm1234567890";
		$target="";
		for ($i=1; $i <= $this->num; $i++) { 
			$xia_biao=mt_rand(0,strlen($zimu)-1);//获取下标
			$dange=$zimu[$xia_biao];//获取下标相应的字符串
			
			//算出每个字母的初始位置
			$x = ($this->width/$this->num)/2-$this->font_size/3+($this->width/$this->num)*($i-1);
			
			$color2=imagecolorallocate($this->src, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));

			// 写入文字
			imagettftext($this->src, $this->font_size, 0, $x, 80, $color2, "./Prisma.ttf", $dange);			
		}
	}

	// 输出图像
	public function output(){
		ob_clean();			//清楚缓存
		imagepng($this->src); 
		imageDestroy($this->src) ;	//释放图像资源

	}











}

 ?>